import { SearchEngin } from '@/config/header-search-engin'
import jspRequest from '@/request/jsonpReq'
import request from '@/request'

interface SearchQuery {
  url: string
  target: SearchEngin
}
export const getSearchOptionsBySite = (query: SearchQuery) => {
  return new Promise(async resolve => {
    let result
    switch (query.target.method) {
      case 'jsonp':
        result = await getJsonpComplete(query.url)
        break

      case 'google jsonp':
        result = await getGetComplete(query.url)
        break

      case 'get':
        result = await getRequestComplete(query.url)
        break
    }

    resolve(result)
  })
}

const getJsonpComplete = (url: string) => {
  return new Promise(resolve => {
    jspRequest({ url }).then((result: any) => {
      let resultList: any[] = []
      if (result.g && result.g.length) {
        resultList = result.g.map((item: any) => {
          return {
            value: item.q,
            text: item.q
          }
        })
      }
      resolve(resultList)
    })
  })
}

const getRequestComplete = (url: string) => {
  return new Promise(resolve => {
    request(url).then(result => {
      console.log('result  :>>', result)
    })
  })
}

const getGetComplete = (url: string) => {
  return new Promise(resolve => {
    jspRequest({
      url,
      customFncName: 'google.ac.h',
      cbName: 'jsonp'
    }).then((result: any) => {
      let resultList: any[] = []
      if (result[0] && result[0].length) {
        resultList = result[0].map((item: any[]) => {
          return {
            value: item[0],
            text: item[0]
          }
        })
      }
      resolve(resultList)
    })
  })
}
